# -*- coding: utf-8 -*-
# @时间：2023/11/3 15:08
# @作者：CJiaの可乐哥
# @文件名：menu
# @软件：Pycharm2023
from typing import List

from ninja import Router, Schema, Field, ModelSchema, Query
from django.shortcuts import get_object_or_404
from system.models import Users, UserRole, Menu, RoleMenu

from utils.cj_tree import list_to_route, list_to_tree
from utils.cj_curd import retrieve, delete, update, status
from utils.cj_response import SuccessResponse, ErrorResponse

router = Router()


class Filters(Schema):
    id: str = Field(None, alias="id")
    title: str = Field(None, alias="title")
    status: bool = Field(None, alias="status")


class MenuSchemaIn(ModelSchema):
    class Config:
        model = Menu
        model_exclude = ['id', 'parent', 'create_datetime', 'update_datetime']


class MenuSchemaOut(ModelSchema):
    class Config:
        model = Menu
        model_fields = "__all__"


@router.delete("/menu/{menu_id}")
def delete_menu(request, menu_id: int):
    request.types = "sys:menu:delete"
    menu = Menu.objects.get(id=menu_id)
    if menu.type == 0:
        return ErrorResponse(msg="目录不支持删除")
    # 调用删除方法
    result = delete(request, menu_id, Menu)
    # 返回结果
    return result


@router.put('/menu/{menu_id}', response=MenuSchemaOut)
def update_menu(request, menu_id: int, data: MenuSchemaIn):
    request.types = "sys:menu:update"
    # 调用修改方法
    result = update(request, menu_id, data, Menu)
    # 返回结果
    return result


@router.put("/menu/status/{menu_id}")
def status_menu(request, menu_id: int):
    request.types = "sys:menu:update"
    menu = Menu.objects.get(id=menu_id)
    if menu.type == 0:
        return ErrorResponse(msg="目录不支持禁用")
    # 调用修改状态方法
    result = status(request, menu_id, Menu)
    # 返回结果
    return result


@router.get("/menu/{menu_id}", response=MenuSchemaOut)
def get_menu(request, menu_id: int):
    menu = get_object_or_404(Menu, id=menu_id)
    return menu


@router.get("/menu", response=List[MenuSchemaOut])
def list_menu_tree(request, filters: Filters = Query(...)):
    qs = retrieve(request, Menu, filters).values()
    # 将查询集转换成树形结构
    menu_tree = list_to_tree(list(qs))
    return SuccessResponse(data=menu_tree)


@router.get("/menu/route/tree")
def menu_route_tree(request):
    """用于前端获取当前角色的路由"""
    user = Users.objects.get(username=request.username)
    queryset = Menu.objects.filter(status=1).values()
    if user.is_superuser == 2:
        role_id = UserRole.objects.get(user_id=user.id).role_id
        menu_ids = RoleMenu.objects.filter(role_id=role_id).values()
        menu_ids = [menu_id['menu_id'] for menu_id in menu_ids]
        queryset = Menu.objects.filter(id__in=menu_ids, status=1).values()
    menu_tree = list_to_route(list(queryset))
    return SuccessResponse(data=menu_tree, msg="获取成功")
